import axios from 'axios'
import { API_BASE_URL } from '@/config'
import { useUserStore } from '@/stores/user'

const http = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000
})

http.interceptors.request.use((config) => {
  const store = useUserStore()
  if (store?.token) {
    config.headers = config.headers || {}
    config.headers.Authorization = `Bearer ${store.token}`
  }
  return config
})

http.interceptors.response.use(
  (res) => res.data,
  (error) => {
    const status = error?.response?.status
    if (status === 401) {
      const store = useUserStore()
      store.logout()
      // optional: redirect to login can be handled in router
    }
    return Promise.reject(error)
  }
)

export default http


